package com.tensquare.friend.interceptor;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
//自定义拦截器
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.得到请求头
        String header = request.getHeader("Authorization");
        //2.判断是否存在
        if(StringUtils.isNotBlank(header)){
            //2.1判断是否以Bearer开头
            if(header.startsWith("Bearer ")){
                //2.1.1从第七位截取获得token字符串
                String token = header.substring(7);
                //2.1.2调用工具类解析token
                Claims claims = jwtUtil.parseToken(token);
                //2.1.3判断claims不为空，就将该对象放入请求作用域
                if(claims!=null){
                    request.setAttribute("claims",claims);
                }
            }
        }
        return true;
    }
}

